#!/bin/bash

work_dir=""
compiler=""
compiler_path=""
install=""
install_path="/opt/qt-5.12.8"
build_example=""
build_type="-r"
build_arg=""
deb_install=""
deb_name="qt-5.12.8"
cpu_core="1"

fun_do_config() {
    processor=$(cat /proc/cpuinfo | grep "processor" | wc -l)
    cpu_core=$(expr ${processor})
    work_dir=$(
        cd "$(dirname "$0")"
        pwd
    )

    rm ${work_dir}/*.deb
    
}

fun_do_set_output() {
    if [ " $work_dir" != " " -a "${work_dir}" != "/" ]; then
        mkdir -p "${work_dir}/$deb_name/DEBIAN"
        mkdir -p "${work_dir}/$deb_name/${install_path}"
    else
        echo "$work_dir is not a directory"
        exit -1
    fi

    env_file='
PATH=$QTDIR/bin:$PATH
MANPATH=$QTDIR/doc/man:$MANPATH
LD_LIBRARY_PATH=$QTDIR/lib:$LD_LIBRARY_PATH
export QTDIR PATH MANPATH LD_LIBRARY_PATH
export QT_PLUGIN_PATH=/opt/qt-5.12.8/plugins
'

    echo '#! /bin/bash' >${work_dir}/$deb_name/${install_path}/env
    echo "QTDIR=$install_path" >>${work_dir}/$deb_name/${install_path}/env
    echo "$env_file" >>${work_dir}/$deb_name/${install_path}/env
    chmod +x ${work_dir}/$deb_name/${install_path}/env
}

fun_do_del_output() {
    if [ " $work_dir" != " " -a "${work_dir}" != "/" ]; then
        sudo rm -rdf "${work_dir}/$deb_name/"
    fi
}

fun_do_help() {
    echo "usage: $0 [-i install path] [-s <on> <off>] [-n <name>]"
    echo "  [-i] install path: install $deb_name path"
    echo "  eg:"
    echo "      $0"
    echo "      $0 -i"
    echo "      $0 -i /usr/lib/"
    echo "      $0 -soff"
    echo "      $0 -son"
}

fun_do_install() {
    install="true"
    if [ " $1" != " " ]; then
        install_path=$1
    fi

}

fun_do_config_shared() {
    if [ " $1" != " " ]; then
        build_shared=$1
    fi
}

fun_do_build_lib() {
    ${work_dir}/auto-config.sh ${work_dir}/$deb_name/${install_path}

}

fun_do_make_deb() {
    sudo make -j $cpu_core
    sudo make install
    $work_dir/build_deb.sh "${work_dir}/$deb_name/" "qt.deb"
}

main() {
    ARGS=$(getopt -o hi::s:: --long help,install::,shared:: -- "$@")
    if [ $? != 0 ]; then
        echo "Terminating..." >&2
        exit 1
    fi
    eval set -- "$ARGS"

    while true; do
        case "$1" in
        -i | --install)
            fun_do_install $2
            shift 2
            ;;
        -s | --shared)
            fun_do_config_shared $2
            shift 2
            ;;
        -h | --help)
            fun_do_help
            shift
            exit 0
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "unknow : {$1}"
            exit 1
            ;;
        esac
    done

    fun_do_config
    fun_do_set_output
    fun_do_build_lib
    fun_do_make_deb
    fun_do_del_output
}

main "$@"
